﻿ALTER PROCEDURE [dbo].[sproc_GIA_DOAN_DUONG_Add]
	@MA_GDD bigint OUTPUT
	,@MA_DKS bigint
	,@GIA_DAT float
	,@NGUOI_KHOI_TAO uniqueidentifier
	,@NGAY_KHOI_TAO datetime
	,@NGAY_CAP_NHAT datetime
	,@ACTIVE_FLAG char(1)

AS
BEGIN
	IF EXISTS (SELECT gdd.MA_DKS FROM GIA_DOAN_DUONG gdd WHERE gdd.MA_DKS=@MA_DKS)
	BEGIN
		UPDATE GIA_DOAN_DUONG
		SET
			GIA_DAT = @GIA_DAT,
			NGAY_KHOI_TAO = @NGAY_KHOI_TAO,
			NGAY_CAP_NHAT = @NGAY_CAP_NHAT
		WHERE MA_DKS=@MA_DKS
		SELECT @MA_GDD=gdd.MA_GDD
		  FROM GIA_DOAN_DUONG gdd WHERE gdd.MA_DKS=@MA_DKS
	END
	ELSE
	BEGIN
		INSERT INTO [GIA_DOAN_DUONG]
		(
			[MA_DKS],
			[GIA_DAT],
			[NGUOI_KHOI_TAO],
			[NGAY_KHOI_TAO],
			[NGAY_CAP_NHAT],
			[ACTIVE_FLAG]
		)
		VALUES
		(
			@MA_DKS,
			@GIA_DAT,
			@NGUOI_KHOI_TAO,
			@NGAY_KHOI_TAO,
			@NGAY_CAP_NHAT,
			@ACTIVE_FLAG
		)
		SELECT
			@MA_GDD = @@Identity
	END
	
	/*
	<root>
		<item value="" date="" />
	</root>
	 */
	IF ISNULL(@MA_GDD,0) != 0
	BEGIN
		DECLARE @History XML
		SET @History=(SELECT HISTORY FROM GIA_DOAN_DUONG gdd WHERE gdd.MA_GDD=@MA_GDD)
		IF cast(ISNULL(@History,'') AS VARCHAR(MAX)) = '' 
		BEGIN
			-- set default value
			SET @History=N'<root/>'
		END 
		DECLARE @Node XML,@Return XML
		set @Node = '<item value="'+cast(@GIA_DAT AS NVARCHAR(20))+'" date="'+CONVERT(VARCHAR(8),GETDATE(),112)+'" />'
		set @Return = convert(xml, (convert(nvarchar(max), @History) + convert(nvarchar(max), @Node)))
		set @Return.modify('insert /*[2] as first into /*[1]')
		set @Return.modify('delete /*[2]')
		
		UPDATE GIA_DOAN_DUONG
		SET
			HISTORY = @Return
		WHERE MA_GDD=@MA_GDD
	END
END